package huanzhao.erp.util;

import org.apache.commons.lang3.StringUtils;

import java.time.Instant;
import java.util.List;
import java.util.Objects;

/**
 * @author April
 * @version 1.0
 */
public class CommonUtil {
    public static TimestampResult handleTimestamp(Long startTimestamp, Long endTimestamp) {
        boolean validation = true;
        if (startTimestamp != null && startTimestamp <= 0) {
            startTimestamp = null;
        }
        if (endTimestamp != null && endTimestamp <= 0) {
            endTimestamp = null;
        }
        if (endTimestamp != null && startTimestamp != null && (endTimestamp < startTimestamp)) {
            validation = false;
        }
        Instant start = null;
        if (startTimestamp != null) {
            start = Instant.ofEpochMilli(startTimestamp);
            startTimestamp = Math.floorDiv(startTimestamp, 1000);
        }
        Instant end = null;
        if (endTimestamp != null) {
            end = Instant.ofEpochMilli(endTimestamp);
            endTimestamp = Math.floorDiv(endTimestamp, 1000);
        }
        return new TimestampResult(startTimestamp, endTimestamp, start, end, validation);
    }

    public record TimestampResult(Long startTimestamp, Long endTimestamp, Instant start, Instant end,
                                  boolean validation) {
    }

    /**
     * 使一个对象人类可读
     *
     * @param obj 对象信息
     * @return String
     * 2024/6/12 下午3:47:12
     */
    public static String readable(Object obj) {
        if (obj == null) {
            return "未指明";
        }
        // 若对象为布尔值
        if (obj instanceof Boolean) {
            return (Boolean) obj ? "是" : "否";
        }
        String string = obj.toString();
        if (StringUtils.isBlank(string)) {
            return "未指明";
        }
        return string;
    }

    public static String[] toStringArray(Object[] objects) {
        if (objects == null) {
            return new String[0];
        }
        String[] strings = new String[objects.length];
        for (int i = 0; i < objects.length; i++) {
            strings[i] = Objects.toString(objects[i], "");
        }
        return strings;
    }

    public static String[] toStringArray(List<?> objects) {
        if (objects == null) {
            return new String[0];
        }
        String[] strings = new String[objects.size()];
        for (int i = 0; i < objects.size(); i++) {
            strings[i] = Objects.toString(objects.get(i), "");
        }
        return strings;
    }
}
